package com.tonghl.juc.queue_study.code;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Created by tonghl
 *
 * 阻塞队列
 *    2.1阻塞队列的好处
 *    2.2不得不阻塞时，你如何处理
 *
 */
public class BlockingQueueDemo {

    public static void main(String[] args) throws  Exception {

        BlockingQueue<String> blockingQueue=new ArrayBlockingQueue(3);
        //throwgroup(blockingQueue);
       // nothrowexpgroup(blockingQueue);

        //nothrowexpgroup2(blockingQueue);

        System.out.println(blockingQueue.offer("a", 2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.offer("a", 2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.offer("a", 2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.offer("a", 2L, TimeUnit.SECONDS));

    }

    public static void nothrowexpgroup2(BlockingQueue<String> blockingQueue) throws InterruptedException {
        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
        blockingQueue.put("x");


        blockingQueue.take();
        blockingQueue.take();
        blockingQueue.take();
        blockingQueue.take();
    }

    /**
     * 温和的一组方法不会抛出异常
     * @param blockingQueue
     */
    public static void nothrowexpgroup(BlockingQueue<String> blockingQueue) {
        //插入
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));
        System.out.println(blockingQueue.offer("x"));
        //检查
        System.out.println(blockingQueue.peek());
        //移除
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
    }

    /**
     * 抛出异常组
     * @param blockingQueue
     */
    public static void throwgroup(BlockingQueue<String> blockingQueue) {
        //插入 易抛异常
        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("b"));
        System.out.println(blockingQueue.add("c"));
        //检查元素
        System.out.println(blockingQueue.element());
        //移除 易抛异常
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
    }
}
